package com.gnerv.sylvanas.framework.plugin.freemarker.listener;

import com.gnerv.sylvanas.framework.plugin.freemarker.FreemarkerComponent;
import com.gnerv.sylvanas.framework.plugin.freemarker.tools.FreemarkerTools;
import freemarker.template.Configuration;
import freemarker.template.TemplateModelException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Gnerv LiGen
 */
@Slf4j
@Component
public class ApplicationContextEventListener implements ApplicationListener<ApplicationContextEvent> {

    @Resource
    private Configuration configuration;

    @Override
    public void onApplicationEvent(ApplicationContextEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(FreemarkerComponent.class);
        for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
            try {
                configuration.setSharedVariable(entry.getKey(), entry.getValue());
            } catch (TemplateModelException e) {
                log.error(e.getMessage(), e);
            }
        }
        FreemarkerTools.setConfiguration(configuration);
    }
}